<!--区域管理-->
<template>
    <div class="minW1060-auto bg-fff mt10">
        <div class="pad20">

            <!--条件查询-->
            <el-row class="text-left">
                <el-col :span="18">
                    <div class="dlblock-mb20">
                        <span class="pr5 ml10">区域类型</span>
                        <el-select class="w150" clearable name="type" v-model="param.types">
                            <el-option label="限速区域" value="1"></el-option>
                            <el-option label="停车场" value="2"></el-option>
                            <el-option label="加油站充电区" value="3"></el-option>
                            <el-option label="告警区域" value="4"></el-option>
                            <el-option label="出租车站点" value="5"></el-option>
                        </el-select>
                    </div>

                    <div class="dlblock-mb20">
                        <span class="pr5 ml10">区域形状</span>
                        <el-select class="w150" clearable name="type" v-model="param.shapes">
                            <el-option label="多边形" value="1"></el-option>
                            <el-option label="圆形" value="3"></el-option>
                        </el-select>
                    </div>

                    <div class="dlblock-mb20">
                        <span class="pr5 ml10">区域名称</span>
                        <el-input
                                v-model.trim="param.name"
                                size="medium"
                                placeholder="请输入区域名称"
                                style="width: 200px;"
                                :maxlength="10"
                                show-word-limit
                                clearable
                        ></el-input>
                    </div>

                    <div class="dlblock-mb20 pr5 pl5">
                        <el-button @click="param.page = 1,queryArea(param)" class="el-icon-search ml5"
                                   circle></el-button>
                    </div>
                </el-col>

                <el-col :span="6" align="right">
                    <div class="dlblock-mb20 pr10 ml20">
                        <el-button @click="addArea" type="primary">添加</el-button>
                    </div>

                    <div class="dlblock-mb20 pr10">
                        <el-button type="danger" @click="deleteAll">删除</el-button>
                    </div>
                </el-col>
            </el-row>

            <!--编辑弹出框-->
            <el-row>
                <el-dialog
                        title="区域管理"
                        :visible.sync="dialogVisible"
                        width="60%"
                        :before-close="handleClose">

                    <!--标签页-->
                    <el-tabs v-model="activeName" @tab-click="handleClick">
                        <el-tab-pane label="基本信息" name="first">
                            <el-form label-position="right" :model="ruleForm" :rules="rules" ref="ruleForm"
                                     label-width="150px">

                                <el-form-item label="区域名称" prop="areaName">
                                    <el-input placeholder="请输入区域名称" style="width: 250px" clearable maxlength="10"
                                              show-word-limit
                                              v-model.trim="ruleForm.areaName"></el-input>
                                </el-form-item>
                                <el-form-item label="区域类型" prop="regionType">
                                    <el-select style="width: 250px" v-model="ruleForm.regionType" clearable
                                               placeholder="请选择区域类型">
                                        <el-option label="限速区域" :value="1"></el-option>
                                        <el-option label="停车场" :value="2"></el-option>
                                        <el-option label="加油站充电区" :value="3"></el-option>
                                        <el-option label="告警区域" :value="4"></el-option>
                                        <el-option label="出租车站点" :value="5"></el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item v-if="ruleForm.regionType==1" prop="dynamicValue" label=" 最高时速">
                                    <el-input style="width: 250px" clearable v-model.trim="ruleForm.dynamicValue"
                                              type="text"
                                              maxlength="10"
                                              show-word-limit
                                              placeholder="最高时速"/>
                                </el-form-item>
                                <el-form-item v-else-if="ruleForm.regionType==2" prop="dynamicValue" label=" 可停车辆数">
                                    <el-input style="width: 250px" clearable v-model.trim="ruleForm.dynamicValue"
                                              type="text"
                                              maxlength="10"
                                              show-word-limit
                                              placeholder="可停车辆数"/>
                                </el-form-item>
                            </el-form>
                        </el-tab-pane>
                        <el-tab-pane label="区域绘制" name="second">
                            <div id="allmap" style="overflow:hidden;zoom:1;position:relative;">
                                <div id="map"
                                     style="width:100%;height:500px;-webkit-transition: all 0.5s ease-in-out;transition: all 0.5s ease-in-out;">
                                </div>
                            </div>
                            <br/>
                            <div id="result">
                                <el-button type="primary" @click="clearAll()"> 清除所有区域
                                </el-button>
                                <el-button type="primary" @click="savePoints">保存区域
                                </el-button>
                            </div>
                        </el-tab-pane>
                    </el-tabs>

                    <span slot="footer" class="dialog-footer">
                        <el-button @click="cancelEditor">取 消</el-button>
                        <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
                    </span>
                </el-dialog>
            </el-row>

            <!--列表页-->
            <el-row>
                <el-table
                        class="my-table"
                        :data="areaList" stripe
                        :header-row-class-name="'my-table-header'"
                        @selection-change="handleSelectionChange"
                        ref="myTable" v-loading="loading"
                        border>

                    <!--复选框-->
                    <el-table-column type="selection" width="55"></el-table-column>

                    <el-table-column align="center" prop="areaName" label="区域位置">
                        <template slot-scope="row">
                            <img width="300px" height="110px" :src="imgurl[row.$index]"/>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="areaName" label="区域名称">
                    </el-table-column>
                    <el-table-column align="center" prop="regionTypeName" label="区域类型">
                    </el-table-column>
                    <el-table-column align="center" prop="shapeTypeName" label="区域形状">
                    </el-table-column>
                    <el-table-column align="center" label="操作" fixed="right">
                        <template slot-scope="{row}">
                            <el-button @click="editor(row.regionId)" type="text">编辑</el-button>
                            <el-button type="text" style="color: #f56c6c" @click="delArea(row.regionId)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-row>

            <br/>
            <!--分页控件-->
            <el-row :gutter="20">
                <el-col :span="12" :offset="6" align="center">
                    <el-pagination background layout="total, prev, pager, next"
                                   :total="param.total"
                                   :page-size="param.size"
                                   :current-page="param.page" @current-change="pageChange">
                    </el-pagination>
                </el-col>
            </el-row>
        </div>

    </div>
</template>

<script>
    import {addPoints, deleteArea, getAreas, getOneArea, insertArea} from '@/api';
    import qs from 'qs'
    // 引入异步引入地图的方法

    export default {

        name: "index",
        components: {},

        data() {
            return {
                /*
                百度地图
                * */
                //已绘制地图数量 集合
                overlays: [],
                map: null,
                mapController: false,
                //百度地图返回对象
                type: '',
                shapeType: 0,
                pointList: [],
                radius: '',

                //中心点
                longitude: '',
                latitude: '',
                zoom: '',


                //回显图形 echo
                echoPolygon: '',
                echoCircle: '',

                //地图图片地址
                imgurl: [],

                temps: [],

                //百度地图
                path: '',
                //所有点的集合
                pts: [],

                //取消点集合
                cancelPts: [],
                //取消图形形状
                cancelShape: '',

                drawingManager: null,

                allOverlay: '',

                area: {
                    type: '',
                },


                //表单验证属性
                ruleForm: {
                    areaName: '',
                    regionType: '',
                    dynamicValue: ''
                },

                //表单验证规则数据
                rules: {
                    areaName: [
                        {required: true, message: '请输入区域名称', trigger: 'blur'},
                    ],
                    regionType: [
                        {required: true, message: '请选择区域类型', trigger: 'change'}
                    ],
                    dynamicValue: [
                        {required: true, message: '数值不能为空', trigger: 'blur'}
                    ],
                },

                //弹出框控制变量
                dialogVisible: false,

                //标签页控制变量
                activeName: 'first',

                //区域数据集合
                areaList: [],

                param: {
                    name: '',
                    types: '',
                    shapes: '',
                    total: 0,
                    size: 6,
                    page: 1
                },

                //全选id
                areaIds: [],

                //加载动画
                loading: true,

                actNav: "",

                //添加还是编辑
                add: true,

                //显示地图
                pathPolygon: '',
                x: '',
                y: '',

            }
        },

        watch: {
            'echoPolygon.ha': function () {

                if (this.shapeType === 1) {
                    //多边形
                    if (this.echoPolygon.Ao != null && this.echoPolygon.Ao.length > 0) {
                        this.shapeType = 1
                        this.pointList = []
                        for (let i = 0; i < this.echoPolygon.Ao.length; i++) {
                            this.pointList.push({
                                lat: this.echoPolygon.Ao[i].lat,
                                lng: this.echoPolygon.Ao[i].lng,
                            })
                        }
                    }
                }

                if (this.shapeType === 3) {
                    //圆形
                    this.pointList = []
                    this.shapeType = 3
                    this.latitude = (this.echoPolygon.point.lat)
                    this.longitude = (this.echoPolygon.point.lng)
                    this.radius = parseInt(this.echoPolygon.xa)

                    for (let i = 0; i < this.echoPolygon.ha.length; i++) {
                        this.pointList.push({
                            lat: this.echoPolygon.ha[i].lat,
                            lng: this.echoPolygon.ha[i].lng,
                        })
                    }
                }

            },

        },

        methods: {

            //编辑取消
            cancelEditor() {
                this.dialogVisible = false
                this.ruleForm = {}
                this.areaIds = []
                this.pointList = []
                this.radius = ''
                this.clearAll()
                this.activeName = 'first'
            },

            //删除全部
            deleteAll() {
                if (this.areaIds.length != 0) {
                    this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        let ids = this.areaIds
                        deleteArea(ids).then(res => {
                            if (res.code == 200) {
                                this.$message({type: 'success', message: '删除成功'});
                                this.queryArea()
                            } else {
                                this.$message({type: 'error', message: '删除失败'});
                            }
                        })
                    }).catch(() => {
                        this.$message({type: 'info', message: '已取消删除'});
                    });
                } else {
                    this.$message({type: 'error', message: '请先选择需要删除的区域'});
                }
            },

            //保存区域
            savePoints() {
                if (this.areaIds.length === 0) {
                    this.$confirm('请先保存基本信息', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    })
                } else {
                    addPoints({
                        regionId: this.areaIds[0],
                        pointsList: this.pointList,
                        radius: this.radius,
                        latitude5: this.latitude,
                        longitude5: this.longitude
                    }).then(
                        result => {
                            if (result.code === 200) {
                                this.$message({type: 'success', message: '区域保存成功'});
                            }
                        }
                    )
                }
            },

            //多选
            handleSelectionChange(val) {
                this.areaIds = []
                val.forEach(x => {
                    this.areaIds.push(x.regionId)
                });
            },

            //区域编辑
            editor(regionId) {
                this.areaIds.push(regionId)
                this.dialogVisible = true
                this.add = false

                getOneArea(qs.stringify({regionId: regionId})).then(
                    result => {
                        if (result.code === 200) {
                            this.ruleForm = result.data
                            this.latitude = result.data.latitude5
                            this.longitude = result.data.longitude5
                            this.radius = result.data.radius
                            this.shapeType = result.data.shapeType
                            this.pointList = result.data.pointsList

                        }
                    }
                )
            },

            //表单验证执行函数
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        insertArea({
                            regionId: this.ruleForm.regionId,
                            name: this.ruleForm.areaName,
                            regionType: this.ruleForm.regionType,
                            shapeType: this.shapeType,
                            value: this.ruleForm.dynamicValue
                        }).then(
                            result => {
                                if (result.code == 200) {
                                    this.dialogVisible = false
                                    this.ruleForm = {}
                                    this.activeName = 'first'
                                    this.queryArea()
                                }
                            }
                        )

                    } else {
                        this.activeName = 'first'
                        return false;
                    }
                });
            },

            //标签页点击事件
            handleClick(tab, event) {

                if (tab.name == "second") {
                    if (!this.add) {
                        this.getCenter()
                    }

                    let that = this
                    setTimeout(function () {

                        that.map = new BMap.Map("map", {
                            enableMapClick: false // 禁止底图点击事件
                        });

                        //圆形
                        if (that.shapeType === 3) {
                            //半径
                            let radius = that.ruleForm.radius;
                            let point = new BMap.Point(that.longitude, that.latitude);
                            let zoom = that.zoom
                            that.map.centerAndZoom(point, zoom + 1);

                            that.echoPolygon = new BMap.Circle(point, radius, {
                                fillColor: "blue",
                                strokeWeight: 1,
                                fillOpacity: 0.3,
                                strokeOpacity: 0.3
                            })
                            that.map.addOverlay(that.echoPolygon);
                            //开启可编辑
                            that.echoPolygon.enableEditing();
                        }

                        //多边形
                        if (that.shapeType === 1) {
                            let point = new BMap.Point(that.longitude, that.latitude);
                            that.map.centerAndZoom(point, that.zoom);

                            //创建多边形标注
                            let temps = [];
                            let arrays = that.pointList;
                            for (let i = 0; i < arrays.length; i++) {
                                let lng = arrays[i].lng;
                                let lat = arrays[i].lat;
                                let pt = new BMap.Point(lng, lat);
                                temps.push(pt);
                            }
                            that.echoPolygon = new BMap.Polygon(temps,
                                {strokeColor: "blue", strokeWeight: 6, strokeOpacity: 0.5}
                            );
                            that.map.addOverlay(that.echoPolygon);

                            //开启可编辑
                            that.echoPolygon.enableEditing();

                        }

                        if (that.shapeType === 0) {
                            that.map.centerAndZoom(new BMap.Point(116.403963, 39.915111), 17);
                        }

                        that.map.enableScrollWheelZoom();
                        //开启定位
                        that.map.addControl(new BMap.GeolocationControl());
                        //地图类型(地图 卫星 三维)
                        //this.map.addControl(new BMap. MapTypeControl());

                        that.map.enableMapClick = false;

                        //实例化鼠标绘制工具
                        that.drawingManager = new BMapLib.DrawingManager(that.map, {
                            isOpen: true, //是否开启绘制模式
                            enableDrawingTool: true, //是否显示工具栏
                            drawingToolOptions: {
                                anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
                                offset: new BMap.Size(5, 5), //偏离值
                                drawingModes: [ // 可见的操作选项
                                    // BMAP_DRAWING_MARKER,
                                    //圆形
                                    BMAP_DRAWING_CIRCLE,
                                    // BMAP_DRAWING_POLYLINE,
                                    //多边形
                                    BMAP_DRAWING_POLYGON,
                                    //矩形
                                    BMAP_DRAWING_RECTANGLE
                                ]
                            },

                        });

                        //添加鼠标绘制工具监听事件，用于获取绘制结果
                        that.drawingManager.addEventListener('overlaycomplete', that.overlaycomplete);
                    }, 10);
                }

            },

            /*  百度地图*/
            //清除绘制区域
            clearAll() {
                this.map.getOverlays()
                this.allOverlay = this.map.getOverlays();
                for (let i = 0; i < this.allOverlay.length - 1; i++) {
                    this.map.removeOverlay(this.allOverlay[i]);
                }

                for (let j = 0; j < this.overlays.length; j++) {
                    this.map.removeOverlay(this.overlays[j]);
                }

                this.echoPolygon = null
                this.allOverlay.length = 0
                this.overlays.length = 0;
                this.pointList = []
                this.shapeType = 0
            },

            //获取 覆盖物
            overlaycomplete(e) {

                this.overlays.push(e.overlay);

                if (this.overlays.length == 0) {
                    this.pointList = []
                } else if (this.overlays.length > 1 || this.echoPolygon != null) {
                    alert("只能绘制一个区域！！！")
                    this.map.getOverlays()
                    this.allOverlay = this.map.getOverlays();

                    for (let i = 0; i < this.allOverlay.length - 1; i++) {
                        this.map.removeOverlay(this.allOverlay[i]);
                    }

                    for (let j = 0; j < this.overlays.length; j++) {
                        this.map.removeOverlay(this.overlays[j]);
                    }

                    this.echoPolygon = null
                    this.allOverlay.length = 0
                    this.overlays.length = 0;

                } else {
                    var path = e.overlay.getPath(); //Array<Point> 返回多边型的点数组
                    if (path != null) {
                        this.pointList = path

                        //多边形
                        if (e.drawingMode == "rectangle") {
                            this.shapeType = 1
                            this.radius = 0
                            this.latitude = 0
                            this.longitude = 0
                        }

                        //圆形
                        if (e.drawingMode == "circle") {
                            this.shapeType = 3
                            this.latitude = this.overlays[0].point.lat
                            this.longitude = this.overlays[0].point.lng
                            this.radius = parseInt(this.overlays[0].xa)
                        }
                    }
                }
            },

            //确认关闭弹出框
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {
                    });
            },

            //添加区域
            addArea() {
                this.dialogVisible = true
                this.add = true
            },

            //查询区域
            queryArea() {
                getAreas({
                    pageNum: this.param.page,
                    areaName: this.param.name,
                    regionType: this.param.types,
                    shapeType: this.param.shapes
                }).then(
                    result => {
                        if (result.code == 200) {

                            this.areaList = result.data.list
                            this.param.total = result.data.count
                            this.param.size = result.data.pageSize

                            this.imgurl = []
                            //获取百度图片地址
                            this.areaList.forEach(item => {
                                this.pointList = item.pointsList
                                this.shapeType = item.shapeType
                                this.getCenter()
                                if (item.shapeType === 3) {
                                    let pathPolygon = ''
                                    for (let i = 0; i < item.pointsList.length; i++) {
                                        pathPolygon = pathPolygon + parseFloat(item.pointsList[i].lng) + ',' + parseFloat(item.pointsList[i].lat) + ';'
                                    }
                                    let latitude = item.latitude5
                                    let longitude = item.longitude5
                                    let url = `http://api.map.baidu.com/staticimage/v2?ak=0MA953dkYQM4fQriWe6NaII8QpjeCCZh&center=${longitude},${latitude}&width=300&height=110&zoom=${this.zoom}&paths=${pathPolygon}&pathStyles=0xff0000,5,0.9,0xffffff&bbox=500,500;500,500 `
                                    this.imgurl.push(url)
                                }
                                if (item.shapeType === 1) {
                                    var urlPolygon = `http://api.map.baidu.com/staticimage/v2?ak=0MA953dkYQM4fQriWe6NaII8QpjeCCZh&center=${this.longitude},${this.latitude}&width=300&height=110&zoom=${this.zoom}&paths=${this.pathPolygon}&pathStyles=0xff0000,5,0.9,0xffffff&bbox=500,500;500,500 `
                                    this.imgurl.push(urlPolygon)
                                }
                                if (item.shapeType === 0) {
                                    this.imgurl.push("")
                                }

                                //用完记得还回来
                                this.shapeType = 0

                                this.loading = false
                            })

                        }
                    }
                )
            },

            delArea(id) {
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let ids = []
                    ids.push(id)
                    deleteArea(ids).then(res => {
                        if (res != null && res.code == 200) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.queryArea()
                        } else {
                            this.$message({
                                type: 'success',
                                message: '删除失败!'
                            });
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },


            /* 分页查询*/
            pageChange(val) {
                this.param.page = val
                this.queryArea()
            },

            //根据经纬极值计算绽放级别
            getZoom(maxLng, minLng, maxLat, minLat) {
                this.map = new BMap.Map();
                var zoom = ["50", "100", "200", "500", "1000", "2000", "5000", "10000", "20000", "25000", "50000", "100000", "200000", "500000", "1000000", "2000000"]//级别18到3。
                var pointA = new BMap.Point(maxLng, maxLat);  // 创建点坐标A
                var pointB = new BMap.Point(minLng, minLat);  // 创建点坐标B
                var distance = this.map.getDistance(pointA, pointB).toFixed(1);  //获取两点距离,保留小数点后两位
                for (var i = 0, zoomLen = zoom.length; i < zoomLen; i++) {
                    if (zoom[i] - distance > 0) {
                        return 18 - i + 1;//之所以会多3，是因为地图范围常常是比例尺距离的10倍以上。所以级别会增加3。
                    }
                }
            },

            //获取zoom 和 中心点
            getCenter() {

                if (this.pointList != null && this.pointList.length > 0) {

                    let maxLng = this.pointList[0].lng;
                    let minLng = this.pointList[0].lng;
                    let maxLat = this.pointList[0].lat;
                    let minLat = this.pointList[0].lat;

                    for (let i = 1; i < this.pointList.length; i++) {
                        let cut = this.pointList[i].lng;
                        cut > maxLng ? maxLng = cut : null;
                        cut < minLng ? minLng = cut : null;
                        let cur = this.pointList[i].lat;
                        cur > maxLat ? maxLat = cur : null;
                        cur < minLat ? minLat = cur : null;
                    }

                    this.zoom = this.getZoom(maxLng, minLng, maxLat, minLat);

                    if (this.shapeType === 1) {
                        let x = 0.0;
                        let y = 0.0;
                        this.pathPolygon = ''
                        for (let i = 0; i < this.pointList.length; i++) {
                            x = x + parseFloat(this.pointList[i].lng);
                            y = y + parseFloat(this.pointList[i].lat);
                            this.pathPolygon = this.pathPolygon + parseFloat(this.pointList[i].lng) + ',' + parseFloat(this.pointList[i].lat) + ';'
                        }
                        this.longitude = (x / this.pointList.length);
                        this.latitude = (y / this.pointList.length);

                    }
                }

            },

        }
        ,

        created() {
            this.queryArea()
        }
        ,

        mounted() {

        }

    }

</script>

<style>
    .my-table /deep/ tr, .my-table /deep/ td {
        padding: 5px !important;
        height: 30px;
        line-height: 30px;
    }

</style>

<style lang="scss">
</style>
<style lang="scss" scoped>
</style>
